/*
 *  *****************************************************************************
 *  * Copyright (C) 2022 szjzsoft Co.,Ltd
 *  * All Rights Reserved.
 *  * 本软件为深圳市金政软件技术有限公司（平台）研制。未经本公司正式书面同意，其他任何个人、团体
 *  * 不得使用、复制、修改或发布本软件.
 *  ****************************************************************************
 */

package cc.bookcloud.tool.ocr.controller.ocr;

import cc.bookcloud.tool.ocr.common.parsetext.InvoiceFeatureFactory;
import cc.bookcloud.tool.ocr.common.parsetext.OcrTextParseAbstract;
import cc.bookcloud.tool.ocr.common.parsetext.OcrTextParseFactory;
import cc.bookcloud.tool.ocr.common.parsetext.OcrTextParseResult;
import cn.hutool.core.text.UnicodeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import cc.bookcloud.tool.ocr.common.JResult;
import cc.bookcloud.tool.ocr.common.parsetext.feature.InvoiceFeatureBatchFactory;
import cc.bookcloud.tool.ocr.common.parsetext.feature.OcrTextInvoicePartitionEntity;
import cc.bookcloud.tool.ocr.util.OCRContentParseUtil;
import cc.bookcloud.tool.ocr.util.OcrTextResponseTransferUtil;
import cc.bookcloud.tool.ocr.util.StringUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Desc: OCR调用服务接口
 * @version: 2.0
 * @author: John Goo
 * @date: 2024/11/19 14:48
 **/
@Slf4j
@RestController
@RequestMapping("/ocr")
public class OcrApiController {



    // OCR Text算法服务
    public static final String OCR_TEXT_URL = "http://localhost:9000/ocr/rec/get/v4?imgPath=";


    @ApiOperation(value = "ocr验证原型界面")
    @GetMapping("/test/verify")
    public ModelAndView gotoUploadImg(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("pages/ocr/img-upload-1");
        return view;
    }


    /********* 图片服务访问地址 ********/
    public static final String SERVER_IMG_URL = "http://localhost:9901/release/fs/download?relativePath=/fs/#?#";


    // latest,最新的，最不稳定的
    @ApiOperation(value = "上传发票，进入ocr识别界面")
    @PostMapping("/test/upload")
    public ModelAndView gotoOcrRec(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
        long startTime = new Date().getTime();
        String imgPath = null;
        // 保存文件目录
        String rootDir = "D:\\dev-work\\ocr-proj\\mysite\\images\\";
        String fileName = null;

        // 文件上传
        for (MultipartFile file : files) {
            //            // 获取文件名以及后级名
            fileName = file.getOriginalFilename();
            // 重新生成文件名（根据具体情况生成对应文件名）
            //fileName = rootDir+""+fileName;
            try {
                file.transferTo(new File(rootDir + fileName));
                // 关闭文件流
                //file.getInputStream().close();
                imgPath = rootDir + fileName;
            } catch (Exception e) {
                log.error("【上传图片失败】", e);
            }
        }
        String serverImgUrl = SERVER_IMG_URL.replace("#?#", fileName);
        ModelAndView view = new ModelAndView("pages/ocr/ocr-rec-verify-2");
        view.addObject("imgPath", imgPath);
        view.addObject("serverImgUrl", serverImgUrl);
        return view;
    }


    @ApiOperation(value = "ocr图片识别-1")
    @GetMapping("/test/rec/v2_1")
    public JResult imgRec(HttpServletRequest request) {
        long startTime = new Date().getTime();
        String imgPath = request.getParameter("imgPath");

        // 操作类型
        String opType = request.getParameter("opType");

        // 调用OCR算法服务
        OkHttpClient client = new OkHttpClient();

        // OCR算法服务
        String OCR_URL = "http://localhost:9000/ocr/get?imgPath=";

        Request requ = new Request.Builder()
                .url(OCR_URL + imgPath)
                .build();

        String recJsonStr = "{}";
        try {
            Response response = client.newCall(requ).execute();
            if (response.isSuccessful()) {
                //recJsonStr = response.body().string();
                // 解决Unicode的乱码问题
                //recJsonStr = new String(response.body().bytes(), StandardCharsets.UTF_8);
                recJsonStr = UnicodeUtil.toString(response.body().string());
                log.info("=========== ocr识别结果 ：" + recJsonStr);
            } else {
                System.out.println("请求失败: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        log.info("=========== ocr 识别结果 ============");

        // ModelAndView view = new ModelAndView("pages/ocr/ocr-rec-verify");
        if ("1".equals(opType)) {

        } else {

        }
        // ************* jsonStr解析处理 ****************//
        JSONObject data = OCRContentParseUtil.parseSimple(recJsonStr);

        // String dataStr = JSON.toJSONString(data, SerializerFeature.PrettyFormat,SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteNullListAsEmpty);

        // **************************************************
        log.info("打印识别结果：", data);
        //  view.addObject("recJson",data);
        long endTime = new Date().getTime();

        // 消耗时间统计
        long total = endTime - startTime;
        log.info("=========消耗时间总计：" + total + " ms");
        data.put("totalTime", total);
        //view.addObject("totalTime",total);
        return JResult.build().ok(data);
    }


    @ApiOperation(value = "ocr图片识别-2")
    @GetMapping("/test/rec/v2_2")
    public JResult imgRecV22(HttpServletRequest request) {
        long startTime = new Date().getTime();
        String imgPath = request.getParameter("imgPath");

        // 操作类型
        String opType = request.getParameter("opType");

        // 调用OCR算法服务
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(20, TimeUnit.SECONDS) // 设置读取超时时间为10秒
                .build();

        // OCR算法服务
        String OCR_URL = "http://localhost:9000/ocr/rec/get/v2?imgPath=";

        Request requ = new Request.Builder()
                .url(OCR_URL + imgPath)
                .build();

        String recJsonStr = "{}";
        try {
            Response response = client.newCall(requ).execute();
            if (response.isSuccessful()) {
                //recJsonStr = response.body().string();
                // 解决Unicode的乱码问题
                //recJsonStr = new String(response.body().bytes(), StandardCharsets.UTF_8);
                recJsonStr = UnicodeUtil.toString(response.body().string());
                log.info("=========== ocr识别结果 ：" + recJsonStr);
            } else {
                System.out.println("请求失败: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        log.info("=========== ocr 识别结果 ============");
        JSONObject data = JSON.parseObject(recJsonStr);

        // 版本v2.9  [ [],[],[]]
        String arrayStr = data.getString("ocrRet");
        JSONArray outArray = JSONArray.parseArray(arrayStr);
        if (outArray.size() > 0) {
            JSONArray array = JSONArray.parseArray(arrayStr).getJSONArray(0);
            data.put("ocrRet", array);
        }

        // **************************************************
        log.info("打印识别结果：", data);
        //  view.addObject("recJson",data);
        long endTime = new Date().getTime();

        // 消耗时间统计
        long total = endTime - startTime;
        log.info("=========消耗时间总计：" + total + " ms");
        data.put("totalTime", total);
        //view.addObject("totalTime",total);
        return JResult.build().ok(data);
    }





    @ApiOperation(value = "ocr图片识别")
    @PostMapping("/test/rec")
    public ModelAndView ocrRec(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
        long startTime = new Date().getTime();
        // 保存文件目录
        String rootDir = "D:\\dev-work\\ocr-proj\\mysite\\images\\";

        String imgPath = null;

        // 文件上传
        for (MultipartFile file : files) {
            //            // 获取文件名以及后级名
            String fileName = file.getOriginalFilename();
            // 重新生成文件名（根据具体情况生成对应文件名）
            //fileName = rootDir+""+fileName;
            try {
                file.transferTo(new File(rootDir + fileName));
                // 关闭文件流
                //file.getInputStream().close();
                imgPath = rootDir + fileName;
            } catch (Exception e) {
                log.error("【上传图片失败】", e);
            }
        }
        // 调用OCR算法服务
        OkHttpClient client = new OkHttpClient();

        // OCR算法服务
        String OCR_URL = "http://localhost:9000/ocr/get?imgPath=";

        Request requ = new Request.Builder()
                .url(OCR_URL + imgPath)
                .build();

        String recJsonStr = "{}";
        try {
            Response response = client.newCall(requ).execute();
            if (response.isSuccessful()) {
                //recJsonStr = response.body().string();
                // 解决Unicode的乱码问题
                //recJsonStr = new String(response.body().bytes(), StandardCharsets.UTF_8);
                recJsonStr = UnicodeUtil.toString(response.body().string());
                log.info("=========== ocr识别结果 ：" + recJsonStr);
            } else {
                System.out.println("请求失败: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        log.info("=========== ocr 识别结果 ============");

        ModelAndView view = new ModelAndView("pages/ocr/ocr-rec-verify");

        // ************* jsonStr解析处理 ****************//
        JSONObject data = OCRContentParseUtil.parseSimple(recJsonStr);

        String dataStr = JSON.toJSONString(data, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteNullListAsEmpty);

        // **************************************************
        log.info(dataStr);
        view.addObject("recJson", dataStr);
        long endTime = new Date().getTime();

        // 消耗时间统计
        long total = endTime - startTime;
        log.info("=========消耗时间总计：" + total + " ms");
        view.addObject("totalTime", total);
        return view;
    }


    @ApiOperation(value = "ocr图片识别-4:火车票解析(JSON版）")
    @GetMapping("/test/rec/v2_3")
    public JSONObject imgRecTrainTicketV23(HttpServletRequest request) {

        // 定义返回结果值
        JSONObject data = new JSONObject();
        long startTime = new Date().getTime();
        String imgPath = request.getParameter("imgPath");

        // 操作类型
        String opType = request.getParameter("opType");

        // 调用OCR算法服务
        OkHttpClient client = new OkHttpClient();

        // OCR算法服务
        String OCR_URL = "http://localhost:9000/ocr/rec/get/v4?imgPath=";

        Request requ = new Request.Builder()
                .url(OCR_URL + imgPath)
                .build();

        String recJsonStr = "{}";
        try {
            Response response = client.newCall(requ).execute();
            if (response.isSuccessful()) {
                //recJsonStr = response.body().string();
                // 解决Unicode的乱码问题
                //recJsonStr = new String(response.body().bytes(), StandardCharsets.UTF_8);
                recJsonStr = UnicodeUtil.toString(response.body().string());
                log.info("=========== ocr识别结果 ：" + recJsonStr);
            } else {
                System.out.println("请求失败: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        log.info("=========== ocr 解析工厂 ============");
        try {

            OcrTextParseResult result = OcrTextParseFactory.ocrTextRec(recJsonStr);
            data.put("ocrRet", result.getRetJson());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        long endTime = new Date().getTime();
        // 消耗时间统计
        long total = endTime - startTime;
        log.info("=========消耗时间总计：" + total + " ms");
        data.put("totalTime", total);
        data.put("code", 0);
        data.put("msg", "操作成功");
        return data;
    }


    @ApiOperation(value = "ocr图片识别-4:火车票解析(融合版）")
    @GetMapping("/test/rec/v2_4")
    public JSONObject imgRecV24(HttpServletRequest request) {

        // 定义返回结果值
        JSONObject data = new JSONObject();
        long startTime = new Date().getTime();
        String imgPath = request.getParameter("imgPath");

        // 操作类型
        String opType = request.getParameter("opType");

        // 调用OCR算法服务
        OkHttpClient client = new OkHttpClient();

        // OCR算法服务
        String OCR_URL = "http://localhost:9000/ocr/rec/get/v4?imgPath=";

        Request requ = new Request.Builder()
                .url(OCR_URL + imgPath)
                .build();

        String recJsonStr = "{}";
        try {
            Response response = client.newCall(requ).execute();
            if (response.isSuccessful()) {
                //recJsonStr = response.body().string();
                // 解决Unicode的乱码问题
                //recJsonStr = new String(response.body().bytes(), StandardCharsets.UTF_8);
                recJsonStr = UnicodeUtil.toString(response.body().string());
                log.info("=========== ocr识别结果 ：" + recJsonStr);
            } else {
                System.out.println("请求失败: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        log.info("=========== ocr 解析工厂 ============");
        try {

            OcrTextParseResult result = OcrTextParseFactory.ocrTextRec(recJsonStr);
            data.put("ocrRet", result.getRetArray());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        long endTime = new Date().getTime();
        // 消耗时间统计
        long total = endTime - startTime;
        log.info("=========消耗时间总计：" + total + " ms");
        data.put("totalTime", total);
        return data;
    }


    @ApiOperation(value = "ocr图片识别：ocr原生数据")
    @GetMapping("/test/rec/v2_5")
    public JSONObject imgRecV25(HttpServletRequest request) {

        long startTime = new Date().getTime();
        String imgPath = request.getParameter("imgPath");

        // 操作类型
        String opType = request.getParameter("opType");

        // 调用OCR算法服务
        OkHttpClient client = new OkHttpClient();

        // OCR算法服务
        String OCR_URL = "http://localhost:9000/ocr/rec/get/v4?imgPath=";

        Request requ = new Request.Builder()
                .url(OCR_URL + imgPath)
                .build();

        String recJsonStr = "{}";
        try {
            Response response = client.newCall(requ).execute();
            if (response.isSuccessful()) {
                //recJsonStr = response.body().string();
                // 解决Unicode的乱码问题
                //recJsonStr = new String(response.body().bytes(), StandardCharsets.UTF_8);
                recJsonStr = UnicodeUtil.toString(response.body().string());
                log.info("=========== ocr识别结果 ：" + recJsonStr);
            } else {
                System.out.println("请求失败: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 定义返回结果值
        JSONObject data = (JSONObject) JSONObject.parse(recJsonStr);
        // ocr原生数据预处理：1）结构的转换；2）识别发票的类型

        // ......

        long endTime = new Date().getTime();
        // 消耗时间统计
        long total = endTime - startTime;
        log.info("=========消耗时间总计：" + total + " ms");
        data.put("totalTime", total);
        return data;
    }

    @ApiOperation(value = "ocr图片识别-6:火车票解析(多张上下版式）")
    @GetMapping("/test/rec/v2_6")
    public JSONObject imgRecV26(HttpServletRequest request) {

        // 定义返回结果值
        JSONObject data = new JSONObject();
        long startTime = new Date().getTime();
        String imgPath = request.getParameter("imgPath");

        // 操作类型
        String opType = request.getParameter("opType");

        // 调用OCR算法服务
        OkHttpClient client = new OkHttpClient();

        // OCR算法服务
        String OCR_URL = "http://localhost:9000/ocr/rec/get/v4?imgPath=";

        Request requ = new Request.Builder()
                .url(OCR_URL + imgPath)
                .build();

        String recJsonStr = "{}";
        try {
            Response response = client.newCall(requ).execute();
            if (response.isSuccessful()) {
                //recJsonStr = response.body().string();
                // 解决Unicode的乱码问题
                //recJsonStr = new String(response.body().bytes(), StandardCharsets.UTF_8);
                recJsonStr = UnicodeUtil.toString(response.body().string());
                log.info("=========== ocr识别结果 ：" + recJsonStr);
            } else {
                System.out.println("请求失败: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        log.info("=========== ocr 解析工厂 ============");


        List result = OcrTextParseFactory.trainTicketMany(recJsonStr);
        data.put("ocrRet", result);

        long endTime = new Date().getTime();
        // 消耗时间统计
        long total = endTime - startTime;
        log.info("=========消耗时间总计：" + total + " ms");
        data.put("totalTime", total);
        return data;
    }



    @ApiOperation(value = "ocr图片识别-7: 识别发票类型")
    @GetMapping("/test/rec/v2_7")
    public JSONObject identifyType(HttpServletRequest request) {

        long startTime = new Date().getTime();
        String imgPath = request.getParameter("imgPath");

        // 操作类型
        String opType = request.getParameter("opType");

        // 调用OCR算法服务
        OkHttpClient client = new OkHttpClient();

        // OCR算法服务
        String OCR_URL = "http://localhost:9000/ocr/rec/get/v4?imgPath=";

        Request requ = new Request.Builder()
                .url(OCR_URL + imgPath)
                .build();

        String recJsonStr = "{}";
        try {
            Response response = client.newCall(requ).execute();
            if (response.isSuccessful()) {
                //recJsonStr = response.body().string();
                // 解决Unicode的乱码问题
                //recJsonStr = new String(response.body().bytes(), StandardCharsets.UTF_8);
                recJsonStr = UnicodeUtil.toString(response.body().string());
                log.info("=========== ocr识别结果 ：" + recJsonStr);
            } else {
                System.out.println("请求失败: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        log.info("=========== ocr 解析工厂 ============");


        //List result = OcrTextParseFactory.trainTicketMany(recJsonStr);
        InvoiceFeatureFactory featureFactory = new InvoiceFeatureFactory();
        JSONObject data = featureFactory.transferAndIdentifyType(recJsonStr);
      //  data.put("ocrRet", result);

        long endTime = new Date().getTime();
        // 消耗时间统计
        long total = endTime - startTime;
        log.info("=========消耗时间总计：" + total + " ms");
        data.put("totalTime", total);
        return data;
    }

    @ApiOperation(value = "ocr图片识别-8: 发票识别（综合版）")
    @GetMapping("/test/rec/v2_8")
    public JResult ocrTextTransfer(HttpServletRequest request) {
        JResult result = JResult.build();

        long startTime = new Date().getTime();
        String imgPath = request.getParameter("imgPath");

        // 操作类型
        String opType = request.getParameter("opType");

        String recJsonStr = callOcrTextService(imgPath,opType);
        log.info("=========== ocr 解析工厂 ============");
        try {
            InvoiceFeatureFactory featureFactory = new InvoiceFeatureFactory();
            JSONObject data = featureFactory.transferAndIdentifyType(recJsonStr);
            OcrTextParseAbstract textParseEntity = OcrTextParseFactory.textParse(recJsonStr);
            JSONArray array = OcrTextResponseTransferUtil.transferMix2Json(textParseEntity);

            long endTime = new Date().getTime();
            // 消耗时间统计
            long total = endTime - startTime;
            log.info("=========消耗时间总计：" + total + " ms");
            data.put("totalTime", total);
            result.setTotalTime(total);
            result.setData(array);
        }catch (Exception e){
            log.error("[解析发票发生异常]",e);
            result.failed(e.getMessage());
        }
        //
        return result;
    }



    private String callOcrTextService(String imgPath,String opType){

        log.info("【请求OCR算法服务】 imgPath:"+imgPath+",opType:"+opType);
        // 调用OCR算法服务
        OkHttpClient client = new OkHttpClient();

        // OCR算法服务
        String url = OCR_TEXT_URL + imgPath;

        Request requ = new Request.Builder()
                .url(url)
                .build();

        String recJsonStr = "{}";
        try {
            Response response = client.newCall(requ).execute();
            if (response.isSuccessful()) {
                //recJsonStr = response.body().string();
                // 解决Unicode的乱码问题
                //recJsonStr = new String(response.body().bytes(), StandardCharsets.UTF_8);
                recJsonStr = UnicodeUtil.toString(response.body().string());
                log.info("=========== ocr识别结果 ：" + recJsonStr);
            } else {
                System.out.println("请求失败: " + response.code());
            }
        } catch (IOException e) {
            log.error("【OCR 算法服务】识别图片发片异常！",e);
        }
        return recJsonStr;
    }



    @ApiOperation(value = "ocr图片识别-9: 全电子发票（普通发票）")
    @GetMapping("/test/rec/v2_9")
    public JResult electronicInvoiceNormalParse(HttpServletRequest request) {
        JResult result = JResult.build();

        long startTime = new Date().getTime();
        String imgPath = request.getParameter("imgPath");

        // 操作类型
        String opType = request.getParameter("opType");

        String recJsonStr = callOcrTextService(imgPath,opType);
        log.info("=========== ocr 解析工厂 ============");
        try {
            InvoiceFeatureFactory featureFactory = new InvoiceFeatureFactory();
            JSONObject data = featureFactory.transferAndIdentifyType(recJsonStr);

            // 类型判断
            String type = data.getString("type");
            if(StringUtil.isEmpty(type) || !type.contains("vat_electronic_invoice_new")){
                result.failed(4444,"请求的发票类型不正确！当前可以处理【全电子发票（普通发票）】的类型");
                return result;
            }

            // 解析工厂
            OcrTextParseAbstract textParseEntity = OcrTextParseFactory.textParse(recJsonStr);
            JSONArray array = OcrTextResponseTransferUtil.transferMix2Json(textParseEntity);

            long endTime = new Date().getTime();
            // 消耗时间统计
            long total = endTime - startTime;
            log.info("=========消耗时间总计：" + total + " ms");
            data.put("totalTime", total);
            result.setTotalTime(total);
            result.setData(array);

        }catch (Exception e){
            log.error("[解析发票发生异常]",e);
            result.failed(e.getMessage());
        }
        //
        return result;
    }


    @ApiOperation(value = "ocr图片识别-9: 发票分区（坐标）")
    @GetMapping("/test/rec/v3_1")
    public JResult invoiceFeatureDepartition(HttpServletRequest request) {
        JResult result = JResult.build();

        long startTime = new Date().getTime();
        String imgPath = request.getParameter("imgPath");

        // 操作类型
        String opType = request.getParameter("opType");

        String recJsonStr = callOcrTextService(imgPath,opType);
        log.info("=========== ocr 解析工厂 ============");
        try {
            InvoiceFeatureBatchFactory featureFactory = new InvoiceFeatureBatchFactory();
            // List<InvoiceFeatureTemplateAbstract> list = featureFactory.extractInvoiceType(recJsonStr);
           // System.out.println("=== feature list:"+list);
             List<OcrTextInvoicePartitionEntity> list = featureFactory.parsePartition(recJsonStr);


            long endTime = new Date().getTime();
            // 消耗时间统计
            long total = endTime - startTime;
            log.info("=========消耗时间总计：" + total + " ms");
         //   System.out.println(list);
            //data.put("totalTime", total);
            result.setTotalTime(total);
            result.setData(list);

        }catch (Exception e){
            log.error("[解析发票发生异常]",e);
            result.failed(e.getMessage());
        }
        //
        return result;
    }


    @ApiOperation(value = "ocr图片识别-9: 发票分区（数据）")
    @GetMapping("/test/rec/v3_2")
    public JResult invoiceDepartitionData(HttpServletRequest request) {
        JResult result = JResult.build();

        long startTime = new Date().getTime();
        String imgPath = request.getParameter("imgPath");

        // 操作类型
        String opType = request.getParameter("opType");

        List retList = new ArrayList();

        String recJsonStr = callOcrTextService(imgPath,opType);
        log.info("=========== ocr 解析工厂 ============");
        try {
            List<OcrTextParseAbstract> list =  OcrTextParseFactory.textBatchParse(recJsonStr);

            // 过滤掉元数据信息
            list.forEach(item->{
                JSONObject row = (JSONObject) JSONObject.toJSON(item);
                row.remove("elementTemplateList");
                row.remove("metaMap");
                retList.add(row);
            });

            long endTime = new Date().getTime();
            // 消耗时间统计
            long total = endTime - startTime;
            log.info("=========消耗时间总计：" + total + " ms");
            //System.out.println(list);
            //data.put("totalTime", total);
            result.setTotalTime(total);
            result.setData(retList);

        }catch (Exception e){
            log.error("[解析发票发生异常]",e);
            result.failed(e.getMessage());
        }
        //
        return result;
    }




}
